<template>
	<view class="">
		<headerinfo></headerinfo>
		<view class="width60">
			<view class="daozuo">
				<view class="actions">
					<view class="action-item">
						<u-icon name="home" size="40px" color="#de4849"></u-icon>
						<text style="color: #de4849;">首页</text>
					</view>
					<view class="action-item" @click="toPage('/pagesfriend/tabbar/mine')">
						<u-icon name="account" size="40px"></u-icon>
						<text>我的</text>
					</view>
				</view>
			</view>
			<view class="friend_Page" @touchstart="refreshStart" @touchmove="refreshMove" @touchend="refreshEnd"
				style="width: 100%;">
				<refresh ref="refresh" @isRefresh="isRefresh"></refresh>
				<view class="friend">
					<view class="header">
						<i class="iconfont" @click="toPage('/pagesfriend/tabbar/fabu')">&#xe620;</i>
						<view class="tab">
							<span @click="chanegTabbar(index) " :class="tabIndex == index?'active':''"
								v-for="(item,index) in tablist" :key="index">{{item}} <i class="iconfont xiamore"
									v-if="index == 2">&#xe61c;</i></span>

						</view>
						<view class="icons">
							<!-- <i class="iconfont">&#xe61d;</i>
							<i class="iconfont">&#xe63b;</i> -->
						</view>
					</view>


					<view class="cardlist">
						<view class="list" @click.stop="toInfo(item)" v-for="(item,index) in list" :key="index">
							<image @click.stop="toOther(item.username)" :src="item.momentUserRsp.avatar"
								mode="aspectFill" class="logo"></image>
							<view class="label">
								<view class="left">
									<view class="title">
										{{item.momentUserRsp.showName}}
									</view>
									<!-- <view class="time">
										{{item.title}}
									</view> -->
								</view>
								<view class="right" @click.stop="shoucang(item)" v-if="myusername!=item.username">
									<span class="btn" style="font-size: 30rpx;">{{item.focused?'已关注':'关注'}}</span>
									<!-- <i class="iconfont">&#xe621;</i> -->
								</view>
							</view>
							<!-- 	<view class="textbox">
								{{item.title}}
							</view> -->
							<view class="textbox">
								{{item.content}}
							</view>

							<view class="imglist">
								<image :style="{ width: item.imageWidth }" @click.stop="priveImg(item.images,index2)"
									:key="index2" v-for="(item2,index2) in item.images" :src="item2" mode="widthFix">
								</image>
							</view>


							<!-- 	<view class="imgBox" v-if="item.videos && item.videos.length>0">
								<image style="height: auto;" class="bofang" src="@/static/bofang.png" mode="widthFix">
								</image>
								<image class="posterUrl" :src="item.posterUrl" mode="widthFix"
									style="width: 100%;height: auto;">
								</image>
							</view> -->
							<view v-if="item.videos && item.videos.length > 0">
								<video :enable-play-gesture="true" :id="'video'+index" @play="videoPlay(item,index)"
									:poster="item.posterUrl" object-fit="cover" @click.stop
									style="width: 500px; height: 300px;border-radius: 20rpx;" :src="item.videos[0]"
									:autoplay="false"></video>
							</view>

							<view class="location" v-if="item.momentUserRsp.province">
								<i class="iconfont">&#xe65e;</i>
								<span>{{item.momentUserRsp.province}}</span>
								<span
									v-if="item.momentUserRsp.province!=item.momentUserRsp.city && item.momentUserRsp.city">>
									{{item.momentUserRsp.city}}</span>
							</view>
							<view class="">
								<!-- <view class="li" @click.stop="share">
									<i class="iconfont">&#xe63d;</i>
									<span>{{item.videoCoverSeconds}}</span>
								</view> -->
								<view class="mt-4 flex align-center justify-between">
									<view class="li" @click.stop="myFavorite(item)" style="margin-right: 40rpx;">
										<i class="iconfont mr-2" style="color: #25d4d0;"
											v-if="item.myFavorite">&#xe8bc;</i>
										<i class="iconfont mr-2" v-else>&#xe62a;</i>
										<span>{{item.myFavorite?'已收藏':'收藏'}}</span>
									</view>
									<view class="li" @click.stop="fabulous(item)" style="margin-right: 40rpx;">
										<i class="iconfont mr-2" style="color: #25d4d0;"
											v-show="item.myLike">&#xe760;</i>
										<i class="iconfont mr-2" v-show="!item.myLike">&#xe86f;</i>
										<span>{{item.likeCount}}</span>
									</view>
									<view class="li">
										<i class="iconfont mr-2">&#xe71b;</i>
										<span>{{item.commentCount}}</span>
									</view>
								</view>
							</view>
						</view>

						<view class="nomore">
							没有更多了 ~
						</view>
					</view>
				</view>
				<uni-popup ref="popup" type="bottom">
					<share @closeDia="closeDia"></share>
				</uni-popup>
			</view>
		</view>

	</view>


</template>

<script>
	import refresh from '@/components/refresh.vue';
	import share from '@/components/share/share.vue'
	export default {
		components: {
			refresh,
			share
		},
		data() {
			return {
				tablist: ['关注', '推荐', '同城'],
				tabIndex: 1,
				query: {
					cityName: "",
					endDate: '',
					lastDocId: "",
					pageSize: 6,
					startDate: '',
				},
				list: [],
				latitude: '',
				longitude: '',
				nowaddress: '',
				myusername: uni.getStorageSync('username') ? uni.getStorageSync('username') : '',
			};
		},
		created() {
			this.query.lastDocId = ''

			this.changejingweidu()
			uni.$on('checkaddressStyle', (data) => {
				this.tablist[2] = this.nowaddress = this.query.cityName = data
				this.query.lastDocId = ''
				this.getData(1)
			})

		},
		onShow() {
			console.log('pagefriend index onShow', this.tabIndex);
			let dianzan = uni.getStorageSync('dianzan') ? uni.getStorageSync('dianzan') : ''
			let guanzhu = uni.getStorageSync('guanzhu') ? uni.getStorageSync('guanzhu') : ''
			let shoucang = uni.getStorageSync('shoucang') ? uni.getStorageSync('shoucang') : ''

			if (dianzan) {
				this.setdianzan(dianzan)
			}
			if (guanzhu) {
				this.setguanzhu(guanzhu)
			}

			if (shoucang) {
				this.setshoucang(shoucang)
			}
		},
		onReachBottom() {
			console.log('onReachBottom');
			if (this.query.lastDocId) {
				this.getData()
			}
		},
		mounted() {
			this.query.lastDocId = ''
			this.getData(1)
		},
		methods: {
			videoPlay(item, index) {

				let video = uni.createVideoContext("video" + index, this)
				video.play();
				console.log("video" + index + ' play');
				for (var i = 0; i < this.list.length; i++) {
					if (i != index) {
						let video2 = uni.createVideoContext("video" + i, this);
						console.log("video" + i + ' pause');
						video2.pause();
					}
				}
			},
			//收藏
			myFavorite(item) {
				let data = {
					favorite: true,
					momentId: item.docId
				};
				if (item.myFavorite) {
					data.favorite = false;
				}

				console.log(data)
				this.$api2.favoriteUnFavoriteMoment(data).then(res => {
					if (data.favorite) {
						this.$Show.show('收藏成功');
					} else {
						this.$Show.show('取消成功');
					}
					item.myFavorite = !item.myFavorite;

				});
			},
			toPage(url) {
				uni.navigateTo({
					url
				})
			},
			fabulous(item) {
				let data = {
					like: true,
					momentId: item.docId
				};
				if (item.myLike) {
					data.like = false;
				}
				this.$api2.likeUnlikeMoment(data).then(res => {
					if (data.like) {
						this.$Show.show('点赞成功');
						item.likeCount++;
					} else {
						item.likeCount--;
					}


					item.myLike = !item.myLike;
					console.log(item)
					// this.$set(this.newData,"myLike",!this.newData.myLike)
					this.$forceUpdate();
				});
			},
			setdianzan(e) {
				console.log(e)

				this.list.forEach(item => {
					console.log(item)
					if (item.docId == e.id) {
						item.likeCount = e.likeCount
						item.myLike = e.myLike

						uni.removeStorageSync('dianzan')
					}
				})
			},

			setguanzhu(e) {
				console.log(e)

				this.list.forEach(item => {
					if (item.username == e.username) {
						item.focused = e.focused
						uni.removeStorageSync('guanzhu')
					}
				})
			},

			setshoucang(e) {
				console.log('setshoucang', e)
				this.list.forEach(item => {
					console.log(item)
					if (item.docId == e.id) {
						item.myFavorite = e.myFavorite

						uni.removeStorageSync('shoucang')
					}
				})
			},
			// 刷新touch监听
			refreshStart(e) {
				this.$refs.refresh.refreshStart(e);
				console.log('1111');
			},
			refreshMove(e) {
				this.$refs.refresh.refreshMove(e);
			},
			refreshEnd(e) {
				this.$refs.refresh.refreshEnd(e);
			},
			isRefresh() {
				console.log('444');
				this.query.lastDocId = ''
				this.getData(1)
				this.$refs.refresh.endAfter();
			},


			chanegTabbar(index) {
				if (this.tabIndex == index && index == 2) {
					uni.navigateTo({
						url: '/pagesfriend/tabbar/cheekaddress'
					})
				} else {
					console.log('chanegTabbar', index);
					this.tabIndex = index
					this.query.lastDocId = ''
					this.getData(1)
				}

			},
			toOther(username) {
				uni.navigateTo({
					url: `/pagesfriend/tabbar/other?username=${username}`
				})
			},
			changejingweidu() {

				let locationStr = uni.getStorageSync('location')
				console.log('----locationStr', locationStr);
				let needCheckLocation = true
				if (locationStr) {
					let locationJson = JSON.parse(locationStr)
					if (locationJson) {
						let lastTimeChecked = locationJson.lastTimeChecked
						let dateEnd = new Date(); //获取当前时间
						let dateDiff = dateEnd.getTime() - lastTimeChecked; //时间差的毫秒数
						let dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
						let cityName = locationJson.cityInfo.data.city
						console.log('-----locationStr----', cityName, dayDiff);
						if (cityName && dayDiff < 1) {
							this.tablist[2] = this.nowaddress = this.query.cityName = cityName
							needCheckLocation = false
						}
					}
				}
				if (needCheckLocation) {
					console.log('获取经纬度')
					uni.request({
						url: 'https://restapi.amap.com/v3/ip?key=791c891520803eef163e7b06ef899341',
						data: '',
						method: 'get',
						success: (res) => {
							console.log('restapi res', res);
							// 所在城市范围的左下右上对标对 "120.8397067,30.77980118;122.1137989,31.66889673"
							let validRsp = res.data.rectangle && res.data.rectangle.length > 0
							if (validRsp) {
								let jingweidu = res.data.rectangle.split(';')

								let leftBottom = jingweidu[0].split(',')
								let left = leftBottom[0]
								let bottom = leftBottom[1]

								let rightTop = jingweidu[1].split(',')
								let right = rightTop[0]
								let top = rightTop[1]
								console.log(left, bottom, right, top);

								this.longitude = (parseFloat(left) + parseFloat(right)) / 2
								this.latitude = (parseFloat(bottom) + parseFloat(top)) / 2
								console.log('latitude', this.latitude);
								console.log('longitude', this.longitude);

								let province = res.data.province
								let city = res.data.city
								console.log('当前城市', province, city)
								if (city) {
									uni.setStorageSync('location', JSON.stringify({
										"cityInfo": res,
										"lastTimeChecked": new Date().getTime()
									}))
								}

								this.tablist[2] = this.nowaddress = this.query.cityName = city

								console.log(this.tablist)

								this.$forceUpdate()
								let token = uni.getStorageSync('token')
								if (token) {
									// this.getCity()
									let data = {
										province: province,
										city: city,
										latitude: this.latitude,
										longitude: this.longitude,
										businessName: "",
										userId: "",
										username: "",
										appId: ""
									}
									console.log('request param ', data);
									this.$api2.userupdateLocation(data).then(res => {
										console.log('经纬度修改成功')
									})
								}

							} else {
								console.log(
									'高德地图api not enough quota,please charge, https://developer.amap.com/api/webservice/guide/api-advanced/ip !'
								)
							}
						},
					})
				}
			},
			getCity() {
				let data = {
					latitude: this.latitude,
					longitude: this.longitude,
				}
				this.$api2.getCurrentCity(data).then(res => {

					this.$nextTick(() => {
						setTimeout(() => {
							this.tablist[2] = this.nowaddress = res
						}, 30)
					})

					console.log('this.tablist', this.tablist);
				})
			},

			getData(type) {
				if (this.tabIndex == 1) {
					delete this.query.cityName
				} else if (this.tabIndex == 0) {
					delete this.query.cityName
				} else {
					if (!this.query.cityName && this.nowaddress) {
						this.query.cityName = this.nowaddress
					}
				}

				uni.showLoading({
					title: '加载中...'
				});
				if (type == 1) {
					this.query.lastDocId = ''
				}
				console.log('111111111111111111', this.tabIndex);
				let viewMomentFunction = this.$api2.getAllShareMoment
				if (this.tabIndex == 0) {
					viewMomentFunction = this.$api2.getFocusedMoment
					console.log('---getFocusedMoment')
				} else if (this.tabIndex == 1) {
					let token = uni.getStorageSync('token')
					if (token) {
						viewMomentFunction = this.$api2.getAllMoment
						console.log('---getAllMoment')
					} else {
						console.log('---getAllShareMoment')
					}
				} else if (this.tabIndex == 2) {
					viewMomentFunction = this.$api2.getSameCityMoment
					console.log('---getSameCityMoment')
				} else {
					console.log('---other wrong tab ----')
				}
				viewMomentFunction(this.query).then(res => {
					if (type == 1) {
						if (res.list.length > 0) {
							this.list = res.list;
						} else {
							this.list = []
						}
						console.log('type 1', this.list.length);
					} else {
						if (res.list.length > 0) {
							this.list = [...this.list, ...res.list];
						}
						console.log('type more', this.list.length);
					}
					if (res.lastDocId) {
						this.query.lastDocId = res.lastDocId;
					} else {
						this.query.lastDocId = ''
					}
				})
				uni.hideLoading();
			},

			shoucang(item) {
				let data = {
					followeeId: item.username,
					focus: true
				}

				if (item.focused) {
					data.focus = false;
				}

				uni.showLoading({
					title: '加载中...'
				});
				this.$api2.followfocus(data).then(res => {
					if (data.focus) {
						this.$Show.show('关注成功');
					} else {
						this.$Show.show('取消成功');
					}

					item.focused = !item.focused;
					this.list.forEach((e => {
						if (e.username == item.username) {
							e.focused = item.focused
						}
					}))


					uni.hideLoading();

					this.$forceUpdate();
				});
			},
			priveImg(arr, index) {
				uni.previewImage({
					urls: arr,
					current: index
				})
			},
			toInfo(item) {
				console.log('item.focused')
				console.log(item.focused)
				let momentUserRsp = JSON.stringify(item.momentUserRsp)

				console.log('item.focused')
				console.log(item.focused)
				let focused = 0
				if (item.focused) {
					focused = 1
				} else {
					focused = 0
				}
				uni.navigateTo({
					url: `/pagesfriend/tabbar/info?id=${item.docId}&momentUserRsp=${momentUserRsp}&focused=${focused}`
				})
			},
			// 分享到朋友圈
			onShareTimeline() {
				let data = {
					title: '来自好友的分享', // 默认是小程序的名称
					path: `/pagesfriend/tabbar/index`, // 默认是当前页面，必须是以‘/’开头的完整路径
					imageUrl: '', // 图片封面，本地文件路径、网络图片路，支持PNG及JPG，默认当前页面截图，显示图片长宽比是 5:4。
					success: res => {
						// 分享成功
						if (res.errMsg == 'shareAppMessage:ok') {}
					},
					fail: res => {
						// 用户取消
						if (res.errMsg == 'shareAppMessage:fail cancel') {}
						// 分享失败
						if (res.errMsg == 'shareAppMessage:fail') {}
					},
					complete: res => {}
				}
				return data
			},
			// 分享给好友
			onShareAppMessage(options) {

				// 设置菜单中的转发按钮触发转发事件时的转发内容
				var shareObj = {
					title: '来自好友的分享', // 默认是小程序的名称(可以写slogan等)
					desc: '', // 小程序的描述
					path: `/pagesfriend/tabbar/index`, // 默认是当前页面，必须是以‘/’开头的完整路径
					imageUrl: '', // 图片封面，本地文件路径、网络图片路，支持PNG及JPG，默认当前页面截图，显示图片长宽比是 5:4。
					success: function(res) {
						// 转发成功之后的回调

						if (res.errMsg == 'shareAppMessage:ok') {
							console.log(res)

						}
					},

				}

				// 返回shareObj
				return shareObj;
			},
			share() {
				this.$refs.popup.open('bottom')
			},
			closeDia() {
				this.$refs.popup.close()
			},
		}
	};
</script>


<style lang="scss" scoped>
	.location {
		margin-top: 30rpx;
		font-size: 28rpx;
		color: #25d4d0;
		display: flex;
		align-items: center;

		.iconfont {
			margin-right: 3px;
		}
	}

	.imgBox {
		border-radius: 10rpx;
		overflow: hidden;
		position: relative;
		width: 120px;
		height: auto;

		.posterUrl {
			border-radius: 10rpx;

		}

		.bofang {
			position: absolute;
			width: 100rpx;
			left: 50%;
			opacity: .8;
			top: 50%;
			transform: translate(-50%, -50%);
			z-index: 10;
		}
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		background-color: #fff;

		.iconfont {
			font-size: 38rpx;
		}

		.tab {
			span {
				margin: 0 20rpx;
				font-size: 34rpx;
				border-bottom: 2px solid #fff;
				padding-bottom: 15rpx;
			}

			.active {
				font-weight: bold;
				font-size: 42rpx;
				border-color: #25d4d0
			}
		}

		.icons {
			display: flex;
			align-items: center;

			.iconfont {
				margin-left: 20rpx;
			}
		}
	}

	.cardlist {
		margin-top: 20rpx;

		.list {
			padding: 30rpx;
			position: relative;
			padding-left: 120rpx;

			.logo {
				position: absolute;
				left: 20rpx;
				top: 20rpx;
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
			}

			.label {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 32rpx;

				.title {
					color: #8a8a8a;
				}

				.time {
					color: #a2a2a2;
					font-size: 32rpx;
				}
			}

			.right {
				display: flex;
				align-items: center;

				.btn {
					padding: 13rpx 40rpx;
					border: 1px solid #25d4d0;
					border-radius: 40px;
					color: #25d4d0;
					margin-right: 20rpx;
				}
			}

			.caozuo {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.li {
					display: flex;
					align-items: center;
					color: #6f6f6f;
					font-size: 30rpx;
					margin-right: 10rpx;

					.iconfont {
						margin-right: 10rpx;
						color: #6f6f6f;
					}
				}

				.list {
					display: flex;
					align-items: center;
				}
			}
		}

		.textbox {
			margin: 30rpx 0;
			font-size: 34rpx;
		}

		.imglist {
			display: flex;
			align-items: center;
			flex-wrap: wrap;

			image {
				width: 120px;
				height: auto;
				border-radius: 20rpx;
				margin-bottom: 20rpx;
				margin-right: 20px;
			}
		}
	}

	.xiamore {
		display: inline-block;
		font-size: 28rpx;
		color: #999;
		margin-left: 10rpx;
	}


	/* 点赞等操作 */
	.actions {
		display: flex;
		align-items: center;
		line-height: 1.3;
		padding-right: 44upx;
		padding-top: 16upx;
		position: fixed;
		left: 0;
		left: 15%;
		flex-direction: column;
		top: 30%;

		.action-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin-right: 60upx;
			color: #333;
			margin-bottom: 80rpx;
			cursor: pointer;

			span {
				font-size: 24rpx;
			}

			.iconfont {
				font-size: 33px;
			}
		}

		.yticon {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 60upx;
			height: 60upx;
			font-size: 52upx;

			&.reverse {
				position: relative;
				top: 6upx;
				transform: scaleY(-1);
			}

			&.active {
				color: #ec706b;
			}
		}

		.icon-fenxiang2 {
			font-weight: bold;
			font-size: 88upx;
		}

		.icon-shoucang {
			font-size: 88upx;
		}
	}
</style>